﻿#include "EditorPackagePageViewModel.h"

#include "Framework/Editor.h"

#include "Asset/EngineDefaultPackage.h"

#include "Project/ProjectModel.h"
#include "Notification/Notification.h"

#include "Async/Process.h"

#include "Path/Paths.h"
#include "File/FileUtils.h"

void REditorPackagePageViewModel::BindModel(TSharedObjectPtr<REditorPageModel> InModel)
{
    Super::BindModel(InModel);
    Model= InModel;

    Icon= REngineDefaultPackage::Get()->GetEngineIcon();
}

TSharedObjectPtr<RTexture2D> REditorPackagePageViewModel::GetIcon() const
{
    return Icon;
}

CString REditorPackagePageViewModel::GetTitle() const
{
    return U"打包项目";
}

CString REditorPackagePageViewModel::GetPlatform() const
{
    return Model->GetPlatform();
}

void REditorPackagePageViewModel::SetOutputPath(const CString &InOutputPath)
{
    Model->OutputPath= InOutputPath;
}

CString REditorPackagePageViewModel::GetOutputPath() const
{
    return Model->OutputPath;
}

void REditorPackagePageViewModel::DeleteItemInOutputFolder()
{
    SPath TargetFolder=Model->OutputPath;
    if(TargetFolder.Exists() && TargetFolder.IsDirectory())
    {
        SFileUtils::ClearDirectory(TargetFolder);
    }
}

void REditorPackagePageViewModel::Package()
{
    SPath EmptyTargetFolder=Model->OutputPath;
    if(EmptyTargetFolder.IsEmpty())
    {
        WHE::AddErrorNotification(U"无法打包项目：目标文件夹不能为空");
        return;
    }

    if(!EmptyTargetFolder.IsEmptyDirectory())
    {
        WHE::AddErrorNotification(U"无法打包项目：目标文件夹必须是一个空文件夹");
        return;
    }
    
    auto ProjectManager=REditor::Get()->GetSubsystem<RProjectModel>();
    if(!ProjectManager->IsProjectOpened())
    {
        WHE::AddErrorNotification(U"无法打包项目：没有打开的项目");
        return;
    }

    CString PackageToolExe=
#ifdef WIN32
    U"ProjectPackager.exe";
#else
    U"ProjectPackager";
#endif

    SPath PackageTool=SPaths::GetExecutablePath().Parent()/PackageToolExe;

    PackageProcess=NewObject<RProcess>(this);

    
    PackageProcess->OnFinished.BindLambda([this](int64_t ExitCode, bool bNormalExit)
    {
        if(bNormalExit)
        {
            WHE::AddInfoNotification(U"项目打包成功");
        }
        else
        {
            WHE::AddErrorNotification(U"项目打包失败");
        }

        this->PackageProcess=nullptr;
    });

    PackageProcess->Start(
    PackageTool.ToString()
    ,{
        CString(U"ProjectDir=")+ProjectManager->GetProjectDirectory().GetValue().ToString(),
        CString(U"OutputDir=")+Model->OutputPath,
        CString(U"ProjectName=")+ProjectManager->GetCurrentProjectInfo().GetValue().Name,
        CString(U"Platform=")+Model->GetPlatform()
    }
    ,true
    ,true);
}
